package com.tezign.intelligence.mini.dam.aifamilyconsultant.interceptor;

import com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.Constant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

	private final RedisTemplate<String, String> redisTemplate;


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		if (request.getMethod().equals("OPTIONS")) {
			//设置了登录全局拦截，会导致跨域的OPTIONS尝试请求被拦截，这里放开
			return true;
		}

		// 检查用户是否已经登录，这里只是一个示例，具体实现可能依赖于你的认证机制
		String userIdStr = request.getHeader(Constant.HEADER_USER_ID);
		if (StringUtils.isEmpty(userIdStr)) {
			// 如果用户未登录，重定向到登录页面或者返回一个错误信息
			// 打印路径
			String requestURI = request.getRequestURI();
			log.error("requestURI:{}", requestURI);
			log.error("userId is null redirect to login page");
			return false;

//			throw new RuntimeException("userId is null redirect to login page");
		}
		String token = request.getHeader(Constant.HEADER_TOKEN);
		if (StringUtils.isEmpty(token)) {
			// 如果用户未登录，重定向到登录页面或者返回一个错误信息
			log.error("token is null, redirect to login page");
			return false;

//			throw new RuntimeException("token is null, redirect to login page");
		}
		String tokenKey = String.format(Constant.TOKEN_PREFIX, userIdStr);
		String tokenValue = redisTemplate.opsForValue().get(tokenKey);
		if (StringUtils.isEmpty(tokenValue) || !token.equals(tokenValue)) {
			// 如果用户未登录，重定向到登录页面或者返回一个错误信息
			log.error("token is invalid, redirect to login page");
			return false;
//			throw new RuntimeException("token is invalid, redirect to login page");
		}

		// 如果用户已登录，继续执行后续操作
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// 可以在请求处理之后进行一些操作，例如添加模型数据
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		// 请求完成后的清理工作
	}
}